using ExamKing.Application.Services;
using ExamKing.WebApp.Job.Dtos;
using Furion.ViewEngine;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Quartz;
using Quartz.Impl.Matchers;
using Quartz.Spi;
using static Quartz.Impl.Matchers.GroupMatcher<Quartz.JobKey>;

namespace ExamKing.WebApp.Job
{
    public class JobController : Controller
    {
        private readonly IViewEngine _viewEngine;

        //调度器工厂
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly IJobFactory _jobFactory;

        public JobController(IViewEngine viewEngine, IJobFactory jobFactory, ISchedulerFactory schedulerFactory)
        {
            _viewEngine = viewEngine;
            _jobFactory = jobFactory;
            _schedulerFactory = schedulerFactory;
        }

        [AllowAnonymous]
        public async Task<IActionResult> Index()
        {
            IScheduler scheduler = await _schedulerFactory.GetScheduler();
            scheduler.JobFactory = _jobFactory;
            var groups = await scheduler.GetJobGroupNames();
            var list = new List<JobDto>();
            foreach (var groupName in groups)
            {
                var jobKeys = await scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(groupName));
                foreach (var jobKey in jobKeys)
                {
                    var jobDto = new JobDto();
                    string jobName = jobKey.Name;
                    string jobGroup = jobKey.Group;
                    var triggers = await scheduler.GetTriggersOfJob(jobKey);
                    jobDto.jobName = jobName;
                    jobDto.jobGroup = jobGroup;
                    foreach (ITrigger trigger in triggers)
                    {
                        trigger.GetNextFireTimeUtc();
                        var triggerTime = TimeZone.CurrentTimeZone.ToLocalTime(
                            Convert.ToDateTime(triggers.ToList()[0].GetNextFireTimeUtc().ToString()));
                        jobDto.triggerTime = triggerTime.ToString();
                    }

                    list.Add(jobDto);
                }
            }

            var vm = new JobModel()
            {
                list = list
            };
            
            return View(vm);
        }
    }
}